﻿using System;
using System.Diagnostics;
using System.IO;

namespace PdfRotator.Util
{
    internal static class PdfUtil
    {
        public static bool Rotate(string path, PdfRotation oddPageRotation, PdfRotation evenPageRotation)
        {
            try
            {
                using (var doc = new PdfDoc(path))
                {
                    doc.ForEach((page, i) =>
                    {
                        var from = page.GetRotate();
                        var to = GetRotation(from, i % 2 == 0 ? oddPageRotation : evenPageRotation);
                        Debug.Print("{0,-5}: {1,3} -> {2,3}", i, from, to);

                        var ret = page.SetRotate(to);
                        Debug.Assert(ret);
                    });
                    return doc.Save(path);
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        private static short GetRotation(short from, PdfRotation rotation)
        {
            switch (rotation)
            {
                case PdfRotation.Rotate0:
                    return from;
                case PdfRotation.Rotate90:
                    return GetRotation(from, 90);
                case PdfRotation.Rotate270:
                    return GetRotation(from, 270);
                case PdfRotation.Rotate180:
                    return GetRotation(from, 180);
                case PdfRotation.SetRotate0:
                    return 0;
                default:
                    throw new ArgumentOutOfRangeException("rotation");
            }
        }

        private static short GetRotation(short from, short offset)
        {
            return (short)((from + offset) % 360);
        }

        public static bool IsPdfFile(string path)
        {
            return String.Equals(".pdf", Path.GetExtension(path), StringComparison.OrdinalIgnoreCase);
        }

        public static bool IsValidPdfFile(string path)
        {
            return IsPdfFile(path) && File.Exists(path);
        }

    }
}
